package com.gitee.hermer.engine.jars.core.eventbus.factory.activemq;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;

import org.apache.activemq.command.ActiveMQObjectMessage;
import org.apache.activemq.command.ActiveMQTextMessage;

import com.gitee.hermer.boot.jee.commons.exception.ErrorCode;
import com.gitee.hermer.boot.jee.commons.log.UtilsContext;
import com.gitee.hermer.boot.jee.commons.reflect.ReflectUtils;
import com.gitee.hermer.boot.jee.commons.verify.Assert;
import com.gitee.hermer.engine.jars.core.app.domain.EngineAppMethodBean;
import com.gitee.hermer.engine.jars.core.eventbus.listener.MessageListener;

public class ActiveMQMessageListener extends UtilsContext implements MessageListener<Message>,ActiveMQSessionMessageListener{


	private EngineAppMethodBean methodBean;
	private Session session;

	private Boolean isUseTransacted;



	public ActiveMQMessageListener(EngineAppMethodBean methodBean,Boolean isUseTransacted){
		this.methodBean = methodBean;
		this.isUseTransacted = isUseTransacted;
	}

	public ClassLoader getClassLoader(){
		return methodBean.getClassLoader();
	}


	@Override
	public void onMessage(Message arg0) {

		try{
			if(isUseTransacted){
				Assert.notNullCode(session, ErrorCode.SYSTEM_ERROR,"Session为空..");
				debug("事务开启 -> messageID[%s]",arg0.getJMSMessageID());
			}
			Object[] t = null;
			if(arg0 instanceof ActiveMQObjectMessage){
				ActiveMQObjectMessage message = ((ActiveMQObjectMessage)arg0);
				if(message.getObject().getClass().isArray()){
					t = (Object[]) message.getObject();
				}else{
					t = new Object[]{message.getObject()};
				}
				Assert.notNull(t);
				ReflectUtils.invoke(methodBean.getBeanObject(), t, methodBean.getMethod());
			}else if(arg0 instanceof ActiveMQTextMessage){
				error("忽略消息 ActiveMQTextMessage -> %s",((ActiveMQTextMessage)arg0).getText());
			}
			if(isUseTransacted){
				session.commit();
			}
		}catch (Throwable e) {
			if(isUseTransacted&& session != null){
				try {
					session.rollback();
				} catch (JMSException e1) {
					error(e1.getMessage(),e1);
				}
			}
			error(e.getMessage(),e);
			error("通知 -> [%s]错误! message:[%s]",e,methodBean.getMethod().toString(),e.getMessage());
		}finally {
		}
	}

	@Override
	public void setQueueSession(Session session) {
		if(session!=null)
			this.session = session;
	}

	@Override
	public void setTopicSession(Session session) {
		if(session!=null)
			this.session = session;
	}

	@Override
	public void destroy() throws Exception {
		session.close();
	}


}
